<!-- 开支编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="640"
    :model-value="modelValue"
    :title="form.id > 0 ? '修改充值' : '充值'"
    @update:modelValue="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="所属公司" prop="tenant_id">
        <TenantChoose v-model="form.tenant_id" :multiple="false" />
      </el-form-item>

      <!-- 快捷月份选择 -->
      <el-form-item label="付款时间" prop="pay_time">
        <el-date-picker
          v-model="form.pay_time"
          type="datetime"
          placeholder="选择时间"
          style="width: 180px"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="到账金额" prop="amount">
        <el-input
          v-model="form.amount"
          style="width: 150px"
          @input="handleInput"
        >
          <template #append>元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="服务费" prop="tax">
        <el-input
          v-model="form.tax"
          style="width: 150px"
          @input="calcFinalAmount"
        >
          <template #append>%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="应付金额" prop="final_amount">
        <el-input v-model="form.final_amount" style="width: 150px" disabled>
          <template #append>元</template>
        </el-input>
      </el-form-item>

      <el-form-item label="备注">
        <el-input clearable v-model="form.remark" style="width: 400px" />
      </el-form-item>
      <el-form-item label="凭证" prop="images">
        <image-upload :limit="1000" v-model="form.images" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="updateModelValue(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch } from 'vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { useFormData } from '@/utils/use-form-data';
  import { tenantPay } from '@/api/company';
  import ImageUpload from '@/components/ImageUpload/index.vue';
  const emit = defineEmits(['done', 'update:modelValue']);

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object,
    companyId: Number
  });

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);

  /** 表单数据 */
  const [form, resetFields, assignFields] = useFormData({
    id: 0,
    tenant_id: '',
    pay_time: '',
    amount: '',
    tax: 3,
    final_amount: '',
    images: '',
    remark: ''
  });

  /** 表单验证规则 */
  const rules = reactive({
    tenant_id: [
      {
        required: true,
        message: '请选择劳务',
        type: 'number',
        trigger: 'blur'
      }
    ],

    pay_time: [
      {
        required: true,
        message: '请选择付款时间',
        type: 'string',
        trigger: 'blur'
      }
    ],

    images: [
      {
        required: true,
        message: '请上传凭证',
        type: 'string',
        trigger: 'blur'
      }
    ],

    amount: [
      {
        required: true,
        message: '请填写金额',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  const handleInput = () => {
    let value = form.amount;

    // 只允许输入数字、小数点和负号
    value = value.replace(/[^\d.-]/g, '');

    // 负号只能出现在最前面
    value = value.replace(/^-+/, '-').replace(/(.)-/g, '$1');

    // 确保只出现一个小数点
    value = value.replace(/(\..*)\./g, '$1');

    // 处理前导零，避免 0001 这种情况，允许 0.x 和 -0.x
    value = value.replace(/^-?0+(\d)/, '-$1');

    form.amount = value;
    calcFinalAmount();
  };

  /** 计算最终的到账金额 */
  /** 计算最终到账金额 */
  const calcFinalAmount = () => {
    const amount = Number(form.amount) || 0;
    const tax = Number(form.tax) || 0;

    const serviceAmount = amount * (tax / 100);
    const finalAmount = amount + serviceAmount;

    form.final_amount = isNaN(finalAmount) ? '0.00' : finalAmount.toFixed(2);
  };

  /** 保存编辑 */
  const save = () => {
    console.log(form);
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      loading.value = true;

      tenantPay(form)
        .then((msg) => {
          loading.value = false;
          EleMessage.success(msg);
          updateModelValue(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          EleMessage.error(e.message);
        });
    });
  };

  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };

  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        if (props.data) {
          assignFields({
            ...props.data
          });
          console.log(form.position_ids, '是什么');
        }
      } else {
        resetFields();
        formRef.value?.clearValidate?.();
      }
    }
  );
</script>
